/*
 * Copyright (c) 2008-2021 浩瀚深度 All Rights Reserved.
 *
 * <p>FileName: IpUtil.java</p>
 *
 * @author zz
 * @date 2024/3/29
 * @version 1.0
 * History:
 * v1.0.0 2024/3/29 Create
 */
package com.haohan.mess.util;
import java.net.Inet6Address;
import java.net.InetAddress;
/**
 * <p>Title: IpUtil</p>
 * <p>Description: </p>
 *
 * @author zz
 */

public class IpUtil {
    public static void main(String[] args) {
        String mixedAddress = "ABCD:0:1234::4567:3456:192.168.1.6";
        String fullIPv6Address = convertMixedToFullIPv6(mixedAddress);
        System.out.println(fullIPv6Address);
    }

    private static String convertMixedToFullIPv6(String mixedAddress) {
        try {
            // 分割 IPv6 和 IPv4 部分
            int lastColon = mixedAddress.lastIndexOf(':');
            String ipv6Part = mixedAddress.substring(0, lastColon + 1);
            String ipv4Part = mixedAddress.substring(lastColon + 1);

            // 将 IPv4 地址转换为十六进制形式的 IPv6 地址
            String[] ipv4Segments = ipv4Part.split("\\.");
            String ipv6FromIPv4 = "";
            for (int i = 0; i < ipv4Segments.length; i += 2) {
                ipv6FromIPv4 += String.format("%02x%02x:", Integer.parseInt(ipv4Segments[i]), Integer.parseInt(ipv4Segments[i + 1]));
            }
            // 移除尾部的冒号
            ipv6FromIPv4 = ipv6FromIPv4.substring(0, ipv6FromIPv4.length() - 1);

            // 完整的 IPv6 地址
            String fullAddress = ipv6Part + ipv6FromIPv4;

            // 使用 InetAddress 来解析完整的 IPv6 地址
            InetAddress inetAddress = Inet6Address.getByName(fullAddress);
            // 转换为规范的形式（小写，展开所有的零）
            return inetAddress.getHostAddress();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
